/**
 * HTML 设置方案
 * #main
 *   <canvas> #top
 *   <div> #zrender
 */

import Panel from '../comps/danmakuPanel';

function createScene(context) {
	let t = new App(context);
	let scene = new context.Scene({
		require : ['zrender'],
		init : (libs) => t.init(libs),
		destroy : () => t.destroy(),
		collectInfo : () => t.collectInfo(),
		onMessage : (key, data) => t.onMessage(key, data),
		onTick : (assetId, data) => t.onTick(assetId, data),
	});
	t.sendStatus = scene.sendStatus;
	return scene;
}

/**
 * 简易版弹幕机
 * 
 * 流程:
 * 1. monitor 需要添加告诉屏幕, 房间号
 * 2. 屏幕这里来创建资源、开启资源、绑定资源
 */

class App {
  roomId = 0;
  danmaku = null;

  // dom
  /** @type {Panel} */
  panel = null;

  constructor(context) {
    this.context = context;
  }

  init(libs) {
    // 先要创建 Dom
    const main = document.getElementById('main');
    const div = document.createElement('div');
    div.id = 'zrender';
    div.style.position = 'absolute';
    div.style.overflow = 'hidden';
    div.style.width = '100%';
    div.style.height = '100%';
    div.style.left = '0px';
    div.style.top = '0px';
    main.appendChild(div);
    const zr = this.zr = libs.zrender.init(div);

    const top = document.createElement("canvas");
    top.id = 'top';
    top.style.width = '100%';
    top.style.height = '100%';
    top.style.position = 'absolute';
    top.style.left = '0px';
    top.style.top = '0px';
    top.style.zIndex = 10;
    top.style.mixBlendMode = 'screen';
		main.appendChild(top);

    this.panel = new Panel({
      zrender : libs.zrender,
      zr, top,
      context : this.context,
      danmaku : this.danmaku
		});

		const roomStr = this.context.parseInitParam().room;
		if (roomStr) {
			const roomId = parseInt(roomStr);
			if (roomId) {
				this.handleAsset(roomId);
			}
		}
  }

  destroy() {
    let content = document.getElementById('canvas');
    if (content) {
      content.remove();
    }
    if (this.zr) {
      this.zr.dispose();
    }
    content = document.getElementById('div');
    if (content) {
      content.remove();
    }
  }
  
  collectInfo() {
    return {
      roomId : this.roomId
    };
  }
  
  onMessage(key, data) {
    switch (key) {
      case 'room': { // monitor 告诉你房间号
        this.handleAsset(data.roomId);
        this.sendStatus();
      } return;
    }
    
    console.log("ribbons 收到无法解析的命令: " + key);
    console.log(data);
  }

  sendStatus() {
    // 等待被覆盖
  }

  onTick(assetId, data) {
    if (this.danmaku != null) {
      this.danmaku.filterAssetTick(assetId, data);
    }
  }

  /**
   * 创建资源、绑定资源
	 * @param {number} roomId B 站房间号, 例如 7734200
   */
  handleAsset(roomId) {
    this.roomId = roomId;

    this.danmaku = new this.context.Danmaku(roomId);
    this.danmaku.createSource()
      .then(() => this.danmaku.openSource())
      .then(() => {
        this.danmaku.onDanmuReceived = (o) => this.panel.onDanmuReceived(o);
        this.danmaku.onEnterReceived = (o) => this.panel.onEnterReceived(o);
      });
  }
}

export default createScene;